﻿using BaseUtils.Helper;
using log4net;
using log4net.Config;
using Newtonsoft.Json;
using System;
using System.Collections.Concurrent;
using System.Threading;
using System.Threading.Tasks;

namespace BaseUtils.Logger
{
    public class LoggerService
    {
        // 使用并发队列来存储日志消息，保证多线程安全
        private static readonly ConcurrentQueue<string> MessageQueue = new ConcurrentQueue<string>();
        // 用于控制后台线程是否持续运行的标识
        private static bool IsRunning = true;
        // 后台线程用于从队列中取出消息并记录日志
        private static Thread BackgroundThread;

        private static readonly ILog log = LogManager.GetLogger(typeof(LoggerService));

        static LoggerService()
        {
            XmlConfigurator.Configure(new System.IO.FileInfo("log4net.config"));
            //BackgroundThread = new Thread(ProcessLogMessageQueue);
            //BackgroundThread.Start();
            Task.Run(() =>
            {
                ProcessLogMessageQueue();
            });
        }

        private static void ProcessLogMessageQueue()
        {
            while (IsRunning || MessageQueue.Count > 0)
            {
                try
                {
                    if (MessageQueue.TryDequeue(out var message))
                    {
                        // 在这里解析消息，根据消息类型等进行相应的日志记录操作
                        // 简单示例，假设消息格式为 "日志级别:实际消息内容"
                        var parts = message.Split(':');
                        if (parts.Length >= 2)
                        {
                            var level = parts[0];
                            var msgContent = message.Replace(parts[0] + ":", "");
                            switch (level.ToLower())
                            {
                                case "info":
                                    log.Info(msgContent);
                                    break;
                                case "warning":
                                    log.Warn(msgContent);
                                    break;
                                case "error":
                                    log.Error(msgContent);
                                    break;
                                default:
                                    log.Info($"未知的日志级别: {message}");
                                    break;
                            }
                            Console.WriteLine(message);
                        }
                    }
                    else
                    {
                        Thread.Sleep(1000);  // 如果队列为空，稍作等待后再尝试
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
        }

        public static void Info(string message, object obj = null)
        {
            message = $"Info:{message};";
            if (obj != null)
            {
                message += JsonConvert.SerializeObject(obj);
            }
            MessageQueue.Enqueue(message);
        }

        public static void Warning(string message, Exception ex = null)
        {
            message = $"Warning:{message};";
            if (ex != null)
            {
                message += " 报错信息：" + ex.Message;
            }
            MessageQueue.Enqueue(message);
        }

        public static void UpdateDataLog(object _old, object _new, object _user)
        {
            try
            {
                string OldMessage = ConvertHelper.ToJson(_old);
                string NewMessage = ConvertHelper.ToJson(_new);
                string UserMessage = ConvertHelper.ToJson(_user);
                Warning("数据被修改：");
                Warning("==============================================");
                Warning($"原数据：{OldMessage}");
                Warning($"新数据：{NewMessage}");
                // MessageQueue.Enqueue($"修改人：{UserMessage}");
                Warning("==============================================");
            }
            catch (Exception ex)
            {
                MessageQueue.Enqueue($"记录异常，{ex.Message};" + ex.StackTrace);
            }
        }

        public static void UpdateDataLog( object _new, object _user)
        {
            try
            {
                string NewMessage = ConvertHelper.ToJson(_new);
                string UserMessage = ConvertHelper.ToJson(_user);
                Warning("添加数据：");
                Warning("==============================================");
                Warning($"新数据：{NewMessage}");
                // MessageQueue.Enqueue($"修改人：{UserMessage}");
                Warning("==============================================");
            }
            catch (Exception ex)
            {
                MessageQueue.Enqueue($"记录异常，{ex.Message};" + ex.StackTrace);
            }
        }
        public static void UpdateDataLog2(object _new, object _user)
        {
            try
            {
                string NewMessage = ConvertHelper.ToJson(_new);
                string UserMessage = ConvertHelper.ToJson(_user);
                Warning("删除数据：");
                Warning("==============================================");
                Warning($"{NewMessage}");
                // MessageQueue.Enqueue($"修改人：{UserMessage}");
                Warning("==============================================");
            }
            catch (Exception ex)
            {
                MessageQueue.Enqueue($"记录异常，{ex.Message};" + ex.StackTrace);
            }
        }
        public static void Error(string message, Exception ex = null)
        {
            message = $"Error:{message}; ";
            if (ex != null)
            {
                message += ";报错信息：" + ex.Message;
            }
            MessageQueue.Enqueue(message);
        }
    }
}
